var express = require("express");
var router = express.Router();
const path = require("path");
const fs = require("fs");
var multiparty = require("multiparty");
const { promisify } = require("util");

const readdir = promisify(fs.readdir);

const UPLOAD_DIR = path.resolve(__dirname);

router.post("/file/upload", async function (req, res) {
  var multipart = new multiparty.Form();
  multipart.parse(req, async function (err, fields, files) {
    if (!files?.chunk) {
      res.send({
        code: 0,
        message: "分片文件上传失败!",
      });
      return;
    }
    const [chunk] = files.chunk;
    const [hash] = fields.hash;
    // 创建临时文件夹用于临时存储chunk
    const chunkDir = path.resolve(UPLOAD_DIR, "chunkDir" + hash.split("_")[0]);
    if (!fs.existsSync(chunkDir)) {
      fs.mkdirSync(chunkDir);
    }

    const targetPath = path.join(path.resolve(UPLOAD_DIR, chunkDir), hash);
    console.log(targetPath, " ====65");
    fs.renameSync(chunk.path, targetPath);

    res.send({
      code: 0,
      message: "OK",
    });
  });
});

router.post("/file/merge", async function (req, res) {
  const { fileHash, fileName } = req.body;
  let suffix = fileName.slice(fileName.lastIndexOf("."));
  try {
    const chunkDir = path.join(__dirname, `chunkDir${fileHash}`);
    const targetFile = path.join(__dirname, fileHash + suffix);
    const chunks = await readdir(chunkDir);
    const sortedChunks = chunks.sort((a, b) => {
      const aNum = parseInt(a.split("_")[1]);
      const bNum = parseInt(b.split("_")[1]);
      return aNum - bNum;
    });

    const writeStream = fs.createWriteStream(targetFile);
    for (const chunk of sortedChunks) {
      const chunkPath = path.join(chunkDir, chunk);
      await new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(chunkPath);
        readStream.pipe(writeStream, { end: false });
        readStream.on("end", resolve);
        readStream.on("error", reject);
      });
    }
    writeStream.end();
    await fs.promises.rm(chunkDir, { recursive: true, force: true });
  } catch {}

  res.send({
    code: 0,
    message: "merge OK",
  });
});

router.post("/file/validate", async function (req, res) {
  let { fileName, fileHash } = req.body;
  let suffix = fileName.slice(fileName.lastIndexOf("."));
  const filePath = path.join(__dirname, fileHash + suffix);
  const chunkDir = path.resolve(UPLOAD_DIR, "chunkDir" + fileHash);
  if (fs.existsSync(filePath)) {
    res.send({
      code: 0,
      message: "文件已上传，无需重复上传!",
    });
  } else if (fs.existsSync(chunkDir)) {
    let files;
    files = fs.readdirSync(chunkDir);
    let list = files.map((file) => {
      const lastIndex = file.lastIndexOf("_");
      return file.slice(lastIndex + 1);
    });
    res.send({
      code: 0,
      data: list,
    });
  } else {
    res.send({
      code: 0,
      tag: true,
    });
  }
});

router.post("/file/cancel", async function (req, res) {
  const { fileHash } = req.body;

  const chunkDir = path.resolve(UPLOAD_DIR, "chunkDir" + fileHash);
  if (fs.existsSync(chunkDir)) {
    await fs.promises.rm(chunkDir, { recursive: true, force: true });
  }
  res.send({
    code: 0,
    message: "OK",
  });
});

module.exports = router;
